package org.dreamwork.jasmine2.web.controls.pdf.controls;

import org.dreamwork.jasmine2.engine.HttpContext;
import org.dreamwork.jasmine2.events.EventException;
import org.dreamwork.jasmine2.util.WebControlCollection;
import org.dreamwork.jasmine2.web.IWebContainer;
import org.dreamwork.jasmine2.web.IWebControl;
import org.dreamwork.jasmine2.web.controls.Literal;
import org.dreamwork.jasmine2.web.controls.pdf.DocumentInfo;
import org.dreamwork.jasmine2.web.controls.pdf.DocumentMetaElement;
import org.dreamwork.jasmine2.web.controls.pdf.MetaElementPosition;
import org.dreamwork.jasmine2.web.html.GenericHtmlControl;
import org.dreamwork.util.StringUtil;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: seth.yang
 * Date: 2010-10-11
 * Time: 13:52:45
 */
public class DocumentControl extends AbstractPDFContainer {
    private DocumentInfo info = new DocumentInfo ();

    public DocumentInfo getInfo () {
        return info;
    }

    @Override
    public void setName (String name) {
        info.setName (name);
    }

    public void setSize (String size) {
        info.setSize (size);
    }

    public void setMargin (String margin) {
        info.setMargin (margin);
    }

    public void setPadding (String padding) {
        info.setPadding (padding);
    }

    @Override
    public void init () {
        HttpContext.current ().setAttribute (PDF_Document_Info_Key, info);
        super.init ();
    }

/*
@page {
	size: a4;
	@top-center { content: element(header-center) };
	@top-left { content: element(header-left) };
	@top-right { content: element(header-right) };
	@bottom-left { content: element(footer-left) };
	@bottom-right { content: element(footer-right) };
}

#pagenumber:before {  content: counter(page);  }
#pagecount:before {  content: counter(pages);  }

@media print {
	div.header-center { display: block; position: running(header-center); padding-top:7mm; padding-bottom:1mm; border-bottom:1px solid #ccc}
	div.header-left {  display: block;  position: running(header-left);  }
	div.header-right {  display: block;  position: running(header-right);  }
	div.footer-left {  display: block;  position: running(footer-left);  }
	div.footer-right {  display: block;  position: running(footer-right); padding-bottom:7mm; border-top:1px solid #ccc}
}
<div id = "border_container">
<div id="header-left" class="header-center" align="center">PDF Created By Jasmine2</div>
<div id="footer-right" class="footer-right" align="right">第 <span id="pagenumber"/>/<span id="pagecount"/> 页</div>
</div>
*/
    @Override
    public void render (PrintWriter writer) throws IOException, EventException {
        super.render (writer);
    }

    @Override
    public void createChildControls () {
        if (page == null) return;

        IWebContainer head = page.getHead ();
        if (head == null) head = page.getBody ();
        if (head == null) head = page.getHtml ();
        if (head == null) head = page;

        IWebContainer body = page.getBody ();
        if (body == null) body = page.getHtml ();
        if (body == null) body = page;

        StringBuilder builder = new StringBuilder ("@page {\r\n");
        StringBuilder print = new StringBuilder ("@media print {\r\n"),
                screen = new StringBuilder ("@media screen {\r\n");

        builder.append ("size: ").append (info.getSize ()).append (';');
        if (!StringUtil.isEmpty (info.getMargin ()))
            builder.append ("margin:").append (info.getMargin ()).append (';');
        if (!StringUtil.isEmpty (info.getPadding ()))
            builder.append ("padding:").append (info.getPadding ()).append (';');

        Map<MetaElementPosition, DocumentMetaElement> elements = info.getMetaElements ();
        if (elements.size () > 0) {
            for (MetaElementPosition mep : elements.keySet ()) {
                DocumentMetaElement dme = elements.get (mep);
                String className = mep.getClassName ();
                String elementId = dme.getApply ();
                if (!checkApplyElement (elementId))
                    throw new RuntimeException ("Can't apply " + className + " to element: " + elementId + ", because the element doesn't exists!");

                boolean createElement = false;
                if (StringUtil.isEmpty (elementId)) {
                    elementId = className;
                    createElement = true;
                }
                builder.append ("\r\n@").append (className).append ('{');
                builder.append ("content:element(").append (elementId).append (")}\r\n");
                print.append ("div#").append (elementId).append ('{');
                print.append ("display: block;  position: running(").append (elementId).append (')');
                if (!StringUtil.isEmpty (dme.getStyle ()))
                    print.append (';').append (dme.getStyle ());
                print.append ("}\r\n");
                screen.append ("div#").append (elementId).append ("{display:none;}\r\n");
                if (createElement) {
                    GenericHtmlControl div = new GenericHtmlControl ("div");
                    div.setId (mep.getClassName ());
                    div.setAttribute ("class", mep.getClassName ());
                    String content = dme.getContent ();
                    if (!StringUtil.isEmpty (content)) {
                        if (content.indexOf ("${pageNumber}") > -1) content = content.replace ("${pageNumber}", "<span id='pagenumber'/>");
                        if (content.indexOf ("${pageCount}") > -1) content = content.replace ("${pageCount}", "<span id='pagecount'/>");
                        if (content.indexOf ("${name}") > -1) content = content.replace ("${name}", info.getName ());
                        div.addControl (new Literal (content));
                    } else {
                        int count = getChildControls ().count ();
                        for (int i = 0; i < count; i ++) {
                            IWebControl c = getControl (i);
                            if (c.getClass () == MetaElementControl.class) {
                                MetaElementControl mec = (MetaElementControl) c;
                                int cs = mec.getChildControls ().count ();
                                for (int j = 0; j < cs; j ++) {
                                    IWebControl f = mec.getControl (j);
                                    if (f.getClass () == MetaContentControl.class) {
                                        MetaContentControl mcc = (MetaContentControl) f;
                                        int x = mcc.getChildControls ().count ();
                                        for (int k = 0; k < x; k ++)
                                            div.addControl (mcc.getControl (k));
                                    }
                                }
                            }
                        }
                    }
                    ((WebControlCollection)body.getChildControls ()).insertControl (0, div);
                }
            }
        }
        builder.append ("}\r\n");
        print.append ("}\r\n");
        screen.append ("}\r\n");

        GenericHtmlControl style = new GenericHtmlControl ("style");
        Literal css = new Literal (builder);
        style.addControl (new Literal ("#pagenumber:before {  content: counter(page);  }\r\n"));
        style.addControl (new Literal ("#pagecount:before {  content: counter(pages);  }\r\n"));
        style.addControl (css);
        style.addControl (new Literal (print));
        head.addControl (style);

        childControls.clear ();
        childControlCreated = true;
    }

    private boolean checkApplyElement (String id) {
        return StringUtil.isEmpty (id) || page.findControl (id) != null;
    }
}